
<!--登录后主要的界面框架-->

<template>
  <el-row type="flex">
    <el-col :style="[{height: windowHeight+'px'}]" :lg="0" :xl="0" class="hidden-md-and-down"><div>0</div></el-col>
    <el-col :style="[{height:windowHeight+'px'}]" :xs="4" :sm="2" :md="2" :lg="3" :xl="4">
<!--      <el-input v-model="tagUid" placeholder="对方的id"></el-input>-->
<!--      <el-button @click="changeTagUid">确定</el-button>-->
<!--      <br/>-->
<!--      消息列表-->
<!--      <br/>-->
      <side-bar-options @toMyInfo="openMyInfoCard" @changeCardContain="changeCardContain" @changeListContain="changeListContain"></side-bar-options>
    </el-col>
    <el-col :style="[{height:windowHeight+'px'}]" :xs="0" :sm="8" :md="7" :lg="5" :xl="6">
      <friend-list @showFriendCard="showFriendCard" :friend-list="myFriendList" v-if="currentList===0" :weidth_H="windowHeight"></friend-list>
      <message-list :friend-list="myFriendList" :windowHeight="windowHeight" @changeMessageCard="changeMsgCard" :all-messages="allMsgList" v-if="currentList===1" :weidth_H="windowHeight" :friend-requests="friendRequeestMsgs" :stomp-client="stompClient"></message-list>

    </el-col>
    <el-col :style="[{height:windowHeight+'px'}]" :xs="20" :sm="14" :md="15" :lg="16" :xl="15">
        <message-contain :allMessages="allMsgList" v-if="currentCard===1" class="right-card-contain" :windowHeight="windowHeight" @deleteMsg="deleteMsg" :message-list="currentMessageList" :friendInfo="currentFirendInfo" :stompClient="stompClient" @sortMsgs="sortMessage(allMsgList)"></message-contain>
<!--      <hello-card v-if="currentCard===0"></hello-card>-->
      <my-card :friend-list="myFriendList" @refresh="refreshMyCard" v-if="currentCard===0"></my-card>
      <search-user-card :allFriendRequest="friendRequeestMsgs" :windowHeight="windowHeight" class="right-card-contain" v-if="currentCard===3" :stomp-client="stompClient"></search-user-card>
    <user-card  @refresh="refreshfriendlist" @toMessageCard="changeMsgCard" @refreshcomment="refreshcomment" :user-info="currentFirendInfo" v-if="currentCard===2"></user-card>
    </el-col>
    <el-col :style="[{height:windowHeight+'px'}]" :lg="0" :xl="0" class="hidden-md-and-down"><div>5</div></el-col>
  </el-row>
</template>
<script>
import 'element-ui/lib/theme-chalk/display.css'
import MessageContain from './cyc/MessageContain.vue'
import UserCard from './FW/UserCard'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import FriendList from './jh/FriendList'

import SideBarOptions from './cyc/SideBarOptions'
import MessageList from './cyc/MessageList'
import SearchUserCard from './cyc/SearchUserCard'
import HelloCard from './cyc/HelloCard'
import common from './cyc/common'
import MyCard from "./FW/MyCard";
export default {
  name: 'MainWindow',
  components: {
      MyCard,
    MessageContain,
    UserCard,
    FriendList,
    HelloCard,
    SideBarOptions,
    MessageList,
    SearchUserCard
  },
  data () {
    return {
      // currentList 当前打开中间的界面，0 好友列表， 1 消息列表
      currentList: 1,
      // currentCard 当前打开最右边的界面，0：欢迎页， 1：聊天页，2： 好友信息, 3: 好友申请
      currentCard: 0,
      tagUid: '',
      windowHeight: window.innerHeight-1,
      currentMessageList: [],
      currentFirendInfo: [],
      stompClient: null,
      Socket: null,
      testUid: '123',
      friendRequeestMsgs: [],
      myFriendList: [],
      unReadMsgs:[],
      allMsgList:[]
    }
  },
  methods: {
    connectWS () {
      var that = this
      var headers = {
        uid: window.localStorage.uid
      }
      if (this.stompClient === null) {
        var socket = new SockJS('/ws/ws')
        this.stompClient = Stomp.over(socket)
        this.stompClient.heartbeat.outgoing = 100000
        this.stompClient.connect(headers,
          function connectionCallback (frame) {
          that.$message.success('web socket 连接成功')
            console.log('连接成功')
            // 这个是私人消息的监听
            that.stompClient.subscribe('/user/topic/chat', function (res) {
              var content = JSON.parse(res.body)
              console.log(content)
              // 如果当前的值是message消息的话
              if (content.fromId != null) {
                that.messageHandle(content)
              }
            },
            function (err) {
              console.log('订阅失败')
              console.log(err)
            })
              // 验证消息的订阅
            that.stompClient.subscribe('/user/topic/friendRequest', function (res) {
              if(res.body === 'true')
              {
                that.getFriendList()
                return
              }
              that.getFriendRequests()
              var content = JSON.parse(res.body)
              console.log(content)
              // 如果别人发个好友请求
              if(content.type === 'receive'){
                that.$notify.info({
                  title: '好友申请',
                  message: content.tagUserInfo.username + '请求添加你为好友'
                })
              }
              // 如果别人回应你的好友请求
              else if(content.type === 'response'){
                if (content.content === "agreement")
                {
                  var message = that.getFriendRequestsUserInfo(content.uid).username + "通过了你的好友请求";
                  that.getFriendList()
                }
                else
                  var message = that.getFriendRequestsUserInfo(content.uid).username + "拒绝了你的好友请求";
                that.$notify.info({
                  title: '好友验证通知',
                  message: message
                })
              }
            }, function (err) {
              console.log("好友申请订阅失败")
              console.log(err)
            })
          },
          function errorCallBack (error) {
          console.log("连接失败")
            console.log(error)
            that.$message.error('web socket 已断开，尝试重新连接')
            that.stompClient = null
            that.connectWS()
          }
        )
      }
      this.socket = socket
    },
    // 取消连接socket
    disconnectWS () {
      var that = this
      if (this.$stompClient != null) {
        this.$stompClient.disconnect(() => {
          console.log('disconnect success!')
        }, {uid: that.userName})
        this.stompClient = null
        that.socket.close()
      }
    },
    messageHandle (message) {
      console.log("messageHandle")
      console.log(this.allMsgList)
      var i = 0;
      for (i = 0 ; i <this.allMsgList.length;i++){
        if (this.allMsgList[i].targetId === message.fromId){
          break
        }
      }
      // 如果之前没有发过消息
      if(i === this.allMsgList.length)
      {
        this.getUnreadMessages();
        this.getAllmessages();
        return;
      }

      var messageRes= {
        sender: 1,
        type: message.type,
        content: message.content,
        time: common('yyyy/MM/dd hh:mm:ss', new Date())
      }
      // 如果当前的id与打开的uid相同
      if(message.fromId === this.currentFirendInfo.uid && this.currentCard === 1) {
        console.log("添加这条消息到内容")
        console.log(message)
        this.currentMessageList.push(messageRes)
      } else{
        if(this.allMsgList[i].unReadCount !== undefined)
        this.allMsgList[i].unReadCount++
        this.allMsgList[i].messages.push(messageRes)
        this.$notify.info({
          title: message.fromId,
          message: message.content
        })
        this.sortMessage(this.allMsgList)
      }
    },
      changeMsgCard(friendInfo){
      this.currentFirendInfo = friendInfo
      this.getMessagesbyTagId(friendInfo.uid)
      this.currentCard = 1
    },
    getMessagesbyTagId(uid){
      for(var i = 0; i<this.allMsgList.length; i++){
        if(this.allMsgList[i].targetId === uid){
          this.currentMessageList = this.allMsgList[i].messages
          return i
        }
      }
    },
    // 获取所有的历史消息,进入页面的时候会获取
    getAllmessages(){
      var that = this
      this.$http(this.$api.getAllMessages, {id: window.localStorage.uid}).then ( res => {
        console.log('获取所有历史消息')
        console.log(res)
        if (res.data === null) {
          window.localStorage.setItem('records', JSON.stringify([]))
          that.allMsgList = []
        } else {
          window.localStorage.setItem('records', JSON.stringify(res.data.records))
          that.allMsgList = res.data.records
          // 获取消息的同时进行排序
          that.sortMessage(that.allMsgList)
        }
      })
    },
    sortMessage(msgs){
        msgs = msgs.sort((a,b)=>{
        let aTime = new Date(a.messages[a.messages.length - 1].time).getTime()
        let bTime = new Date(b.messages[b.messages.length - 1].time).getTime()
        return bTime - aTime
      })
    },
    // 获取未读消息，进入页面的时候获取
    getUnreadMessages () {
      var that = this
      this.$http(this.$api.getUnreadMessages, {uid: window.localStorage.uid}).then( res =>{
        console.log('未读消息')
        console.log(res.data.unreadMessages);
        window.localStorage.setItem('unreadMessages', JSON.stringify(res.data.unreadMessages))
       // that.unReadMsgs = res.data.unreadMessages

      })
    },
    changeListContain(val){
      console.log("changeListContain")
      this.currentList = val
    },
    changeCardContain(val){
      this.currentCard = val
    },
      toMyInfo(val){
        this.currentCard = val
      },
    clickFriendNotify(val){
      console.log("点击")
      console.log(val)

    },
    // 获取 好友申请的用户信息
    getFriendRequestsUserInfo(uid){
      for(let i = 0 ;i<this.friendRequeestMsgs.length;i++) {
        if(this.friendRequeestMsgs[i].tagId === uid) {
          return this.friendRequeestMsgs[i].tagUserInfo
        }
      }
      return null
    },
    // 获取好友申请
    getFriendRequests(){
      var that = this
      this.$http(this.$api.getFriendRequest, {uid: window.localStorage.uid}).then( res=>{
        console.log("获取好友请求")
        console.log(res)
        that.$global_variable.friendRequests = res.data.requests
        that.friendRequeestMsgs = res.data.requests
      })
    },
    getFriendList(){
      var that = this
      this.$http(this.$api.getFriendList, {uid: window.localStorage.uid}).then(res=>{
        console.log("好友列表")
        console.log(res);
        that.myFriendList =  res.data
        that.$global_variable.friendList = res.data
        window.localStorage.setItem("friendList", JSON.stringify(res.data))
      })
    },
      refreshfriendlist(){
          var that = this
          that.getFriendList();
          that.currentCard = 0
      },
      refreshcomment(){
          this.currentCard = -1,
              this.$nextTick(()=>
                  this.currentCard = 2
              )
      },
    // 显示好友详情
    showFriendCard(info){
        if(info!=null)
            this.currentFirendInfo = info
      this.currentCard=1
        this.$nextTick(() => {
            this.currentCard = 2
        })
    },
    openMyInfoCard(){
      this.currentCard = 0
    },
    deleteMsg(uid){
      var that = this
      for(let i = 0; i<this.allMsgList.length;i++){
        if(this.allMsgList[i].targetId === uid){
          this.allMsgList.splice(i,1);
          break
        }
      }
      this.currentCard = 0
      this.$http(this.$api.deleteHistoryRecord,{uid:window.localStorage.uid,tagId: uid}).then(res=>{
        if(res.data === true)
          that.$message.success("删除成功")
        else
          that.$message.error("删除失败，请检查网络并重试")
      })
    },
      refreshMyCard() {
        this.currentCard = -1,
            this.$nextTick(()=>
                this.currentCard = 0
              )
      }
  },
  mounted () {
    var that = this
    window.onresize = () => {
      return (() => {
        that.windowHeight = window.innerHeight - 1
        console.log('change')
      })()
    }
  },
  created () {
    this.connectWS()
   // if(window.localStorage.getItem('records') === undefined)
      this.getAllmessages()
    this.getUnreadMessages();
    this.getFriendRequests();
    this.getFriendList();
    // else
    // this.$global_variable.historyRecords =JSON.parse(window.localStorage.records)

  },
  destroyed () {
    this.disconnectWS()
  }
}
</script>

<style scoped>
  .el-col {
    position: relative;
    overflow: hidden;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 600px;
  }
  .right-card-contain{
    border-style: solid; border-width: 2px; border-color: #E5E9F2;
  }
</style>
